//index.js
const app = getApp() //获取应用实例
let request = require("../../utils/request.js"); //封装的request请求
let log = require('../../utils/log.js')
let saveQRcode = require('../../utils/saveQRcode.js')
let config = require('../../config/config.js')
let countTime = null
let stopingTimer = null
let refFlag = false
let currOrderFlag = false
let payCurrOrderFlag = false
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import websocket from '../../utils/websocket'
var QQMapWx = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({
  key: config.map_key
})
let localTimeout = null
let subInterval = null
let addInterval = null
Page({
  data: {
    token: '',
    stopingCar: [],
    bottomShow: false,
    reorientation: 0,
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    show: false,
    longitude: 0,
    latitude: 0,
    scale: 12,
    userInfo: {},
    markers: [],
    circles: [],
    circlesR: 400,
    includePoints: [],
    hasmarkers: false,
    openId: '',
    remainTime: 0,
    cardNumList: [],
    user: {},
    totalMyTicket: 0,
    haveCard: false,
    carNumber: '',
    parkList: [],
    searcheRecord: [],
    searchPlace: {},
    hasPhone: false,
    showMarkerModal: false,
    stopParkDialog: false,
    stopMyCar: {},
    markerPark: {},
    subscribeStatus: 0,
    searching: [],
    searchPark: [],
    showTabBar: true,
    unfoldRule: false,
    isNotLocation: true,
    searchResult: [],
    noSearchData: false,
    searchAddress: '',
    timerList: [],
    monthList: [],
    monthPayRule: [],
    websocketUrl: '',
    customerLeftTime: {},
    showGoOutPark: false,
    showStop: false,
    mapKey: config.map_key,
    mapStyle: config.map_style,
    changeStyleTime: 10000,
    stopCarDialog: false,
    stopCarOutDialog: false,
    stop_car_tips: '',
    parkImgCurr: 0,
    couponTipList: [],
    couponTipsDialog: false,
    touchStartX: 0,
    touchEndX: 0,
    parkInfoImageL: 0,
    customCalloutMarkerIds: [],
    customCalloutData: [],
    applyCar: [],
    applyCarIds: [],
    applyCarData: [],
    canIUseGetUserProfile: false,
    payBehalfDialog: false,
    behalfList: []
  },
  onLoad: function () {
    let that = this;
    let token = wx.getStorageSync('lmtc_token');
    let userInfo = wx.getStorageSync('lmtc_userInfo');
    that.setData({
      isNotLocation: wx.getStorageSync('lmtc_isLocation') ? false : true, // 是否授权位置信息
      websocketUrl: app.globalData.websocketUrl
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (token) {
      that.setData({
        token: token,
        userInfo
      })
    }
    // 获取用户当前位置
    that.getLocation()
      .then(res => {
        that.getLocal(res.latitude, res.longitude);
        // that.getParks(res.longitude, res.latitude);
      })
      .catch(err => {
        console.log(err);
        that.openUserLocation()
      })
    if (userInfo && !wx.getStorageSync('lmtc_start')) {
      wx.login({
        success: res => {
          let url = '/customer/info/authorize'
          let params = {
            avatar: userInfo.avatarUrl,
            code: res.code,
            nickname: userInfo.nickName,
            sex: userInfo.gender == 0 ? 'UNKNOWN' : userInfo.gender == 1 ? 'MEN' : 'WOMEN',
          }
          request.http(url, 'POST', params)
            .then(res => {
              var data = res.data
              if (data.code == 200) {
                wx.setStorage({
                  data: data.data.token,
                  key: 'lmtc_token',
                  success(res) {
                    wx.setStorageSync('lmtc_start', true)
                    wx.setStorageSync('lmtc_customerId', data.data.customerId)
                    that.setData({
                      websocketUrl: app.globalData.websocketUrl + data.data.customerId
                    })
                    // that.getCustomerLeftTime()
                    // that.getCouponTips()
                    // that.getStopingCar()
                    // that.getCustomerApply()
                    that.openSocket()
                  }
                })
              }
            })
        }
      });
    }
    this.miniProgranUpdate()
  },
  onShow() {
    console.log('index-show')
    // this.closePayBehalfDialog()
    if (wx.getStorageSync('lmtc_token')) {
      // this.getCustomerLeftTime()
      this.getCouponTips()
      // this.getCustomerApply()
      this.toMineBtn()
    }
  },
  onReady() {
    this.MapContext = wx.createMapContext('myMap');
  },
  /**
   * 小程序更新
   */
  miniProgranUpdate() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function () {
      console.log('新版本下载失败');
      // 新版本下载失败
    })
  },
  /**
   * 打开支付垫付费用弹窗
   */
  openPayBehalfDialog(){
    this.setData({ payBehalfDialog: true })
  },
  /**
   * 关闭支付垫付费用弹窗
   */
  closePayBehalfDialog(){
    this.setData({ payBehalfDialog: false })
  },
  /**
   * 开启定位
   */
  openUserLocation() {
    var that = this
    wx.showModal({
      content: '请您先授权位置信息',
      confirmText: '去授权',
      success(res) {
        if (res.confirm) {
          wx.openSetting({
            withSubscriptions: true,
            success(res) {
              that.setData({
                isNotLocation: !res.authSetting['scope.userLocation']
              })
              wx.setStorageSync('lmtc_isLocation', !res.authSetting['scope.userLocation'])
            }
          })
        }
      }
    })
  },
  /**
   * 获取用户当前位置
   */
  getLocation() {
    const that = this
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude,
            includePoints: [{
              longitude: res.longitude,
              latitude: res.latitude
            }],
            hasmarkers: true,
            isNotLocation: false
          });
          wx.setStorageSync('lmtc_isLocation', true)
          resolve(res)
        },
        fail(err) {
          if (err.errCode == 2) {
            if (wx.getSystemInfoSync().locationEnabled == false) {
              if (that.data.reorientation >= 60) {
                wx.showToast({
                  title: '定位失败，请检查您的设备是否开启GPS定位,开起后请重新启动小程序',
                  duration: 30000,
                  icon: 'none'
                })
                return
              }
              wx.showToast({
                title: '定位失败，请检查您的设备是否开启GPS定位',
                duration: 10000,
                icon: 'none'
              })
              localTimeout = setTimeout(function () {
                that.getLocation()
                  .then(res => {
                    that.getLocal(res.latitude, res.longitude);
                    that.getParks(res.longitude, res.latitude);
                  })
              }, 1000)
              that.setData({
                reorientation: that.data.reorientation + 1
              })
            } else {
              wx.showToast({
                title: '定位失败',
                duration: 10000,
                icon: 'none'
              })
            }
          }
          reject(err)
        }
      })
    })
  },
  /**
   * 获取当前地理位置
   * @param {Number} latitude 维度
   * @param {Number} longitude 精度
   */
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city
        })
      },
      fail: function (res) {
        console.log(res);
        // Toast.fail('获取位置失败，请重新登录');
      }
    });
  },
  /**
   * 授权登录
   */
  bindGetUserInfo: function (e) {
    let that = this;
    let url = e.currentTarget.dataset.url
    let userInfo = e.detail.userInfo;
    wx.setStorageSync('lmtc_userInfo', userInfo)
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
      wx.login({
        success: res => {
          that.getToken(res.code, url);
        }
      });
    }
  },
  /**
   * 获取用户信息
   */
  getUserProfile(e) {
    let that = this;
    let url = e.currentTarget.dataset.url
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.setData({
          userInfo: res.userInfo
        })
        wx.setStorageSync('lmtc_userInfo', res.userInfo)
        wx.login({
          success: res => {
            that.getToken(res.code, url);
          }
        });
      }
    })
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   */
  getToken(code, src) {
    let that = this
    let info = this.data.userInfo;
    let url = '/customer/info/authorize'
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
    }
    request.http(url, 'POST', params)
      .then(res => {
        var data = res.data
        log.info('接口' + url + ':' + JSON.stringify(data))
        if (data.code == 200) {
          let token = data.data.token
          wx.setStorageSync('lmtc_token', token)
          wx.setStorageSync('lmtc_customerId', data.data.customerId)
          that.setData({
            token,
            userInfo: wx.getStorageSync('lmtc_userInfo'),
            websocketUrl: app.globalData.websocketUrl + data.data.customerId
          })
          that.getStopingCar()
          that.getCustomerApply()
          that.getCustomerLeftTime()
          that.openSocket()
          that.getCouponTips()
          that.getArrearsOrder()  //  获取垫付订单
          if (src) {
            wx.navigateTo({
              url: src
            })
          }
        } else {
          wx.removeStorageSync('lmtc_userInfo')
        }
      })
  },
  /**
  * 获取用户时长卡/月卡
  */
  getCustomerLeftTime() {
    let that = this
    let url = '/customer/card/getCustomerLeftTime'
    request.http(url, 'GET')
      .then(res => {
        if (res.data.code == 200) {
          that.setData({
            customerLeftTime: res.data.data
          })
        }
      })
  },
      /**
     * 获取垫付订单
     */
    getArrearsOrder(){
      request.http('/order/info-trade-record/get-arrears-order', 'GET')
      .then(res => {  
        this.setData({
          behalfList: res.data.data,
        })
      })
    },
  /**
   * 获取用户停车信息
   */
  getStopingCar(isLoading) {
    let that = this
    let url = '/order/orderInfo/getCustomerCarParkList'
    var isLoading = isLoading == false ? isLoading : true
    request.http(url, 'GET', {}, isLoading)
      .then(res => {
        var data = res.data
        log.info('接口' + url + ':' + JSON.stringify(res.data))
        if (data.code == 200) {
          let markers = that.data.markers
          markers.forEach((element, index) => {
            if ((/^stop/).test(element.id)) {
              delete markers[index]
            }
          });
          let marker = {}
          let customCalloutMarkerIds = []
          let customCalloutData = []
          let stopingCar = data.data
          // let stopingCar = []
          // stopingCar.push(data.data[0])
          // stopingCar.push(
          //   {
          //     orderCode: "A1_2C16027457714406",
          //     parkId: "6669",
          //     parkName: "正式环境测试停车场",
          //     longitude: "114.529737",
          //     latitude: "37.999567",
          //     carNumber: "冀A88888",
          //     inTime: "2020-10-15 15:09:31",
          //     parkingTime: "18:36"
          //   }
          // )
          for (let i = 0; i < stopingCar.length; i++) {
            stopingCar[i].checked = false
            // if (stopingCar[i].canPrePay != 0) {
            that.setData({
              showGoOutPark: true
            })
            // }
            markers.forEach((element, index) => {
              if (stopingCar[i].latitude == element.latitude && stopingCar[i].longitude == element.longitude) {
                markers[index]['customCallout'] = {
                  display: 'ALWAYS',
                  anchorX: 0,
                  anchorY: 0
                }
                customCalloutMarkerIds.push(element.id)
                customCalloutData.push(stopingCar[i].carNumber)
              }
            });
            that.setData({
              stopingCar: stopingCar,
              markers: markers,
              customCalloutMarkerIds: customCalloutMarkerIds,
              customCalloutData: customCalloutData
            })
            // that.timerFr()
          }
          if (stopingCar.length <= 0) {
            that.setData({
              stopingCar: [],
              markers: markers,
              customCalloutMarkerIds: [],
              customCalloutData: []
            })
            return
          }
        }
      })
  },
  timerFr() {
    let that = this
    let timer = []
    let outTime = []
    let customCalloutData = this.data.customCalloutData
    for (var i = 0; i < customCalloutData.length; i++) {
      outTime[i] = 100
      timers(i)
    }
    function timers(index) {
      var dateArr = customCalloutData[i].split(':')
      let time = ''
      time = parseInt(dateArr[0]) == 0 ? parseInt(dateArr[1]) + '分钟' : parseInt(dateArr[0]) + '小时' + parseInt(dateArr[1]) + '分钟'
      // customCalloutData[index] = (parseInt(dateArr[0]) + (parseInt(dateArr[1]) / 60)).toFixed(1)
      customCalloutData[index] = time
      that.setData({
        customCalloutData: customCalloutData
      })
      clearInterval(timer[index])
      timer[index] = setInterval(function () {
        if (dateArr[1] >= 60) {
          dateArr[0] = parseInt(dateArr[0]) + 1
          dateArr[1] = 0
        } else {
          dateArr[1] = parseInt(dateArr[1]) + 1
        }
        customCalloutData[index] = time
        // customCalloutData[index] = (parseInt(dateArr[0]) + (parseInt(dateArr[1]) / 60)).toFixed(1)
        that.setData({
          customCalloutData: customCalloutData
        })
      }, 60000);
    }
  },
  /**
   * 预约坐标点位
   */
  getCustomerApply() {
    let that = this
    request.http('/order-reserve/park-reserve-record/reserved-curr', 'GET')
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let markers = that.data.markers
          let applyCar = data.data
          let applyCarIds = []
          let applyCarData = []
          for (var i = 0; i < applyCar.length; i++) {
            if (applyCar[i].inParkOrderId) {
              continue
            }
            markers.forEach((element, index) => {
              if (applyCar[i].latitude == element.latitude && applyCar[i].longitude == element.longitude) {
                markers[index]['customCallout'] = {
                  display: 'ALWAYS',
                  anchorX: 0,
                  anchorY: 0
                }
                applyCarIds.push(element.id)
                applyCarData.push(applyCar[i].parkingTime)
              }
            });
          }
          that.setData({
            applyCar: applyCar,
            markers: markers,
            applyCarIds: applyCarIds,
            applyCarData: applyCarData
          })
        }
      })
  },
  // 显示停车列表
  showStopList() {
    this.setData({
      showStop: !this.data.showStop
    })
  },
  // 显示实时订单
  showOrder(e) {
    let index = e.currentTarget.dataset.index
    let stopPark = this.data.stopingCar[index]
    this.MapContext.moveToLocation({
      longitude: stopPark.longitude,
      latitude: stopPark.latitude
    })
    this.setData({
      showStop: false
    })
    this.getCurrOrder(index)
  },
  /**
   * 获取附近停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   * @param {Boolean} search 是否搜索
   */
  getParks(longitude, latitude) {
    let that = this;
    let url = '/park/info/getParkList'
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data;

          let markers = [];
          if (parkList != null && parkList.length > 0) {
            for (let i = 0; i < parkList.length; i++) {
              // saveQRcode.saveQRcode(parkList[i])
              let marker = {};
              let iconPath = ''
              if (parkList[i].emptyParkSpace < 10) {
                iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling30_icon.png'
                if (parkList[i].isAutopay == '0') {
                  iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
                }
              } else if (parkList[i].emptyParkSpace >= 10 && parkList[i].emptyParkSpace < 20) {
                iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling30_icon.png'
                if (parkList[i].isAutopay == '0') {
                  iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
                }
              } else if (parkList[i].emptyParkSpace >= 20) {
                iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling30_icon.png'
                if (parkList[i].isAutopay == '0') {
                  iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
                }
              }
              marker = {
                id: i + 1,
                longitude: parkList[i].longitude,
                latitude: parkList[i].latitude,
                iconPath: iconPath,
                width: 31,
                height: 41,
                zIndex: 1400
              }
              markers.push(marker);
            }
            let myMarker = {
              id: 0,
              longitude: longitude,
              latitude: latitude,
              iconPath: 'https://file.zmzncs.com/file/WeChat/location_cion.png',
              width: 25,
              height: 35,
              zIndex: 1500
            }
            markers.unshift(myMarker);
            that.setData({
              parkList: parkList,
              markers: markers,
            })
            clearInterval(subInterval)
            clearInterval(addInterval)
          } else {
            let myMarker = {
              id: 0,
              longitude: longitude,
              latitude: latitude,
              iconPath: 'https://file.zmzncs.com/file/WeChat/location_cion.png',
              width: 25,
              height: 35,
              zIndex: 1500
            }
            markers.unshift(myMarker);
            this.MapContext.includePoints({
              padding: ['50', '50', '60', '50'],
              points: markers,
              success(res) {
                console.log('。。。。。。。。。。。。。。。' + res)
              },
              fail(err) {
                console.log(err)
              }
            })
            that.setData({
              parkList: [],
              markers: markers
            })
            Toast('当前无可用停车场');
          }
          if (longitude !== 0 && latitude !== 0) {
            that.MapContext.moveToLocation({
              longitude,
              latitude
            })
          }
        }
        if (wx.getStorageSync('lmtc_token')) {
          that.getStopingCar()
          that.getCustomerApply()
        }
        that.locationChange()
        refFlag = false
      })
      .catch(res => {
        refFlag = false
      })
  },
  /**
   * 获取用户信息
   * @param {String} userId 用户ID
   */
  getUserInfo(userId) {
    let that = this;
    let url = "/api/cUser/myInfo?userId=" + userId;
    request.http(url, 'post')
      .then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data.user;
          if (user != null && user != undefined) {
            let mobilePhone = user.mobilePhone;
            if (mobilePhone != null && mobilePhone != undefined && mobilePhone != "") {
              that.setData({
                hasPhone: true
              })
            } else {
              that.setData({
                hasPhone: false
              })
            }
            that.setData({
              cardNumList: res.data.data.cardNumList,
              user: user,
              totalMyTicket: res.data.data.totalMyTicket,
              haveCard: res.data.data.haveCard,
              remainTime: res.data.data.remainTime
            })
          }
          if (res.data.data.haveCard) {
            let day = ''
            let endT = ''
            let nowT = new Date().getTime()
            let eleCard = res.data.data.eleCard
            endT = new Date(eleCard.endTime).getTime()
            day = Math.floor((endT - nowT) / 1000 / 60 / 60 / 24)
            eleCard['remainingDay'] = day;
            that.setData({
              eleCard: eleCard,
            })
          }
          let cardNumList = res.data.data.cardNumList;
          if (cardNumList != null && cardNumList != '') {
            if (cardNumList.length == 1) {
              that.setData({
                carNumber: cardNumList[0]
              })
            } else {
              that.setData({
                carNumber: cardNumList.length
              })
            }
          } else {
            that.setData({
              carNumber: ''
            })
          }
        } else {
          Toast.fail('网络错误');
        }
      })
  },
  /**
   * 跳转到我的服务页
   */
  toMine() {
    let token = this.data.token;
    let user = this.data.user;
    if (token == null || token == undefined || token == '') {
      Toast('请先授权');
      return
    } else {
      user = JSON.stringify(user);
      wx.navigateTo({
        url: '../grade/grade',
      })
    }
  },
  /**
   * 关闭中间部分
   */
  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 关闭底部弹窗
   */
  bottomPopClose() {
    this.setData({
      bottomShow: false,
      noSearchData: false,
      searchAddress: '',
      searching: []
    })
  },
  /**
   * 打开底部弹窗
   */
  showBottomPop() {
    let searcheRecord = wx.getStorageSync('searcheRecord');
    if (searcheRecord != null) {
      this.setData({
        searcheRecord: searcheRecord
      })
    }
    this.setData({
      bottomShow: true,
    })

  },
  /**
   * 跳转到会员中心
   */
  toVip(e) {
    let token = this.data.token;
    let type = e.currentTarget.dataset.type
    if (token == null || token == "" || token == undefined) {
      wx.showToast({
        title: '请先授权',
        icon: 'none'
      })
      return
    }
    // wx.navigateTo({
    //   url: '../vipCharge/vipCharge' + (type == 'parkVip' ? '?parkData=' + JSON.stringify(this.data.markerPark) + '&index=1' : ''),
    // })
    wx.navigateTo({
      url: '/pages/pay/monthly/monthly?parkData=' + JSON.stringify(this.data.markerPark),
    })
    this.setData({
      stopCarOutDialog: false
    })
  },
  /**
   * 预约功能
   */
  reservePark() {
    let markerPark = this.data.markerPark
    if (markerPark.reserveParkSpace == 0) {
      wx.showToast({
        title: '对不起，当前停车场暂无预约功能，请尝试预约其他停车场',
        icon: 'none'
      })
      return
    }
    request.http('/promotion/reserve-fee-scale/getMonthRulePaytypeByParkId', 'GET', { parkId: markerPark.id })
      .then(res => {
        wx.navigateTo({
          url: '/pages/subscribe/subscribe?parkId=' + markerPark.id + '&parkName=' + markerPark.parkName + '&reserveParkSpace=' + markerPark.reserveParkSpace,
        })
      })
      .catch(err => {
        wx.showToast({
          title: '对不起，当前停车场暂无预约功能，请尝试预约其他停车场',
          icon: 'none'
        })
      })

  },
  /**
   * 跳转到电子卡页面
   */
  toDredge() {
    let token = this.data.token;
    if (token == null || token == undefined || token == '') {
      Toast('请先授权');
      return
    } else {
      wx.navigateTo({
        url: '../card/card',
      })
    }
  },
  /**
   * 获取搜索输入框的文字
   */
  getSearch(event) {
    let that = this
    this.setData({
      searchAddress: event.detail.value
    })
    // this.searchStopPark(event.detail.value)
    qqmapsdk.getSuggestion({
      keyword: event.detail.value,
      region: this.data.city,
      page_size: 20,
      success(res) {
        var data = res.data
        that.setData({
          searching: data,
          searchResult: []
        })
      }
    })
  },
  /**
   * 搜索停车场
   */
  searchStopPark(val) {
    let that = this
    if (!val) {
      that.setData({
        searchPark: []
      })
      return
    }
    let url = '/park/info/getParkByName'
    let params = {
      keyword: val
    }
    request.http(url, 'GET', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            searchPark: data.data
          })
        }
      })
  },
  /**
   * 搜索到的目位置
   */
  showSearchMapMark(e) {
    let type = e.currentTarget.dataset.type
    let index = e.currentTarget.dataset.index
    let record = {}
    let searching
    if (type == 'park') {
      searching = this.data.searchPark
      record = {
        place: searching[index].parkName,
        latitude: searching[index].latitude,
        longitude: searching[index].longitude,
        address: searching[index].parkAddress
      }
    } else if (type == 'address') {
      searching = this.data.searching
      record = {
        place: searching[index].title,
        latitude: searching[index].location.lat,
        longitude: searching[index].location.lng,
        address: searching[index].address
      }
    }
    var searcheRecord = wx.getStorageSync('searcheRecord');
    if (Array.isArray(searcheRecord)) {
      if (searcheRecord.length == 2) {
        searcheRecord.splice(1, 1);
        searcheRecord.unshift(record);
      } else {
        searcheRecord.unshift(record);
      }
    } else {
      searcheRecord = [];
      searcheRecord.push(record);
    }
    wx.setStorageSync('searcheRecord', searcheRecord);
    this.getNearbyPark(record.longitude, record.latitude)
    this.setData({
      searching: []
    })
  },
  /**
   * 获取附近停车点
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getNearbyPark(longitude, latitude) {
    let that = this
    let record = {
      longitude: longitude,
      latitude: latitude,
      currentPage: 1,
      pageSize: 10
    }
    let url = "/park/info/getNearbyParkList";
    request.http(url, 'GET', record)
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data.records;
          that.setData({
            searchResult: parkList
          })
          if (parkList.length <= 0) {
            wx.showToast({
              title: '当前地点附近暂无停车场可用',
              icon: 'none'
            })
          }
        }
      })
  },
  /**
   * 在地图上显示停车点
   * @param {*} e 
   */
  showParkMapMark(e, data) {
    let that = this
    let searchResult
    if (e) {
      let index = e.currentTarget.dataset.index
      searchResult = this.data.searchResult[index]
    } else {
      searchResult = data
    }
    let iconPath = 'https://file.zmzncs.com/file/WeChat//index_canParks_0.png'
    let markers = this.data.markers
    this.bottomPopClose();
    if (searchResult.emptyParkSpace < 10) {
      iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling3_icon.png'
      if (searchResult.isAutopay == '0') {
        iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
      }
    } else if (searchResult.emptyParkSpace >= 10 && searchResult.emptyParkSpace < 20) {
      iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling30_icon.png'
      if (searchResult.isAutopay == '0') {
        iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
      }
    } else if (searchResult.emptyParkSpace >= 20) {
      iconPath = 'https://file.zmzncs.com/file/WeChat/notfeeling30_icon.png'
      if (searchResult.isAutopay == '0') {
        iconPath = 'https://file.zmzncs.com/file/WeChat/payment20_icon.png'
      }
    }

    for (var i = 0; i < markers.length; i++) {
      if (markers[i]) {
        if (/^search/.test(markers[i].id)) {
          delete markers[i]
        }
      }
    }
    let myMarker = {
      id: 'search' + 0,
      longitude: searchResult.longitude,
      latitude: searchResult.latitude,
      iconPath: iconPath,
      width: 31,
      height: 41,
      label: {
        content: '目标位置',
        zIndex: 1500,
        anchorX: -24,
        anchorY: -56,
        fontSize: '12px'
      },
      zIndex: 1500
    }
    markers.unshift(myMarker);
    this.MapContext.moveToLocation({
      longitude: searchResult.longitude,
      latitude: searchResult.latitude
    })
    this.calculateDistance(
      {
        longitude: that.data.longitude,
        latitude: that.data.latitude
      },
      [
        {
          longitude: searchResult.longitude,
          latitude: searchResult.latitude
        }
      ],
      function (res) {
        let distances = (res.result.elements[0].distance / 1000).toFixed(2)
        let url = '/park/info/getParkInfoById'
        request.http(url, 'GET', { parkId: searchResult.id })
          .then(res => {
            let data = res.data
            if (data.code == 200) {
              let parkInfo = data.data
              parkInfo['distances'] = distances
              parkInfo['id'] = searchResult.id
              that.setData({
                markerPark: parkInfo,
                targetPark: parkInfo,
                showMarkerModal: true
              })
            }
          })
      }
    )
    let markerPark = {
      parkName: searchResult.parkName,
      id: searchResult.id,
      parkAddress: searchResult.parkAddress,
      parkImgUrl: searchResult.parkImgUrl,
      distances: searchResult.distances,
      priceDesc: searchResult.priceDesc,
      emptyParkSpace: searchResult.emptyParkSpace,
      reserveParkSpace: searchResult.reserveParkSpace,
      pileSum: searchResult.pileSum,
      longitude: searchResult.longitude,
      latitude: searchResult.latitude
    }
    this.setData({
      // showMarkerModal: true,
      // targetPark: markerPark,
      // markerPark,
      markers
    })
  },
  /**
   * 在地图中显示标记点
   */
  showMapMark(e) {
    let data = e.currentTarget.dataset
    if (!data.name) {
      let parkInfo = this.data.parkList[data.index]
      this.showParkMapMark(false, parkInfo)
    } else {
      this.setData({
        searchAddress: data.name
      })
      this.getNearbyPark(data.lon, data.lat)
    }
  },
  //续卡
  toChargeCard() {
    let that = this;
    let token = that.data.token;
    if (token == null || token == undefined || token == '') {
      Toast('请先授权');
      return
    }
    wx.navigateTo({
      url: '../grade/grade'
    })
  },
  /**
   * 点击地图上的标记
   * @param {*} e 
   */
  checkMarkerPark(e) {
    if (this.data.showMarkerModal) {
      return
    }
    let id = e.detail.markerId;
    let that = this;
    if (id == 0) {
      Toast('这是您当前位置');
      this.setData({
        showMarkerModal: false
      })
      return
    }
    if (/^stop/.test(id)) {
      if (currOrderFlag) {
        return
      }
      currOrderFlag = true
      id = id.substring(4)
      that.getCurrOrder(id)
    } else if (/^search/.test(id)) {
      that.setData({
        markerPark: that.data.targetPark,
        // showTabBar: true,
        showMarkerModal: true
      })
      that.MapContext.moveToLocation({
        longitude: that.data.targetPark.longitude,
        latitude: that.data.targetPark.latitude
      })
    } else {
      let index = id - 1;
      let parkList = that.data.parkList;
      that.MapContext.moveToLocation({
        longitude: parkList[index].longitude,
        latitude: parkList[index].latitude
      })
      that.calculateDistance(
        {
          longitude: that.data.longitude,
          latitude: that.data.latitude
        },
        [
          {
            longitude: parkList[index].longitude,
            latitude: parkList[index].latitude
          }
        ],
        function (res) {
          let distances = (res.result.elements[0].distance / 1000).toFixed(2)
          let url = '/park/info/getParkInfoById'
          request.http(url, 'GET', { parkId: parkList[index].id })
            .then(res => {
              let data = res.data
              if (data.code == 200) {
                let parkInfo = data.data
                parkInfo['distances'] = distances
                parkInfo['id'] = parkList[index].id
                that.setData({
                  markerPark: parkInfo,
                  showMarkerModal: true
                })
              }
            })
        }
      )
    }
  },
  // 地图上的自定义气泡
  checkStopPark(e) {
    let id = e.detail.markerId
    let stopCar = this.data.stopingCar
    let applyCar = this.data.applyCar
    let markers = this.data.markers
    let index = 0
    if (applyCar.length > 0) {
      for (var i = 0; i < applyCar.length; i++) {
        if (markers[id].latitude == applyCar[i].latitude && markers[id].longitude == applyCar[i].longitude) {
          return
        }
      }
    }
    for (var i = 0; i < stopCar.length; i++) {
      if (markers[id].latitude == stopCar[i].latitude && markers[id].longitude == stopCar[i].longitude) {
        index = i
      }
    }
    stopCar[index].checked = true
    this.setData({
      stopCarOutDialog: true,
      stopingCar: stopCar
    })
    this.getCurrOrder(index, true)
  },
  /**
   * 获取车主实时订单
   * @param {boolean} isOut 是否点击外部离场按钮
   */
  getCurrOrder(index, isOut) {
    let that = this
    let url = '/order/orderInfo/queryCurrOrder'
    let stopingCar = that.data.stopingCar
    let paramsList = []
    paramsList.push({
      orderCode: stopingCar[index].orderCode,
      parkId: stopingCar[index].parkId,
      carNumber: stopingCar[index].carNumber
    })
    let params = {
      list: paramsList
    }
    request.http(url, 'GET', params, 1)
      .then(res => {
        log.info('接口' + url + ':' + JSON.stringify(res.data))
        if (res.data.code == 200) {
          let data = res.data.data
          let time = ''
          for (var i = 0; i < data.length; i++) {
            time = Math.floor(data[i].duration / 60) > 0 ? Math.floor(data[i].duration / 60) + '小时' + data[i].duration % 60 + '分钟' : data[i].duration % 60 + '分钟'
            data[i].duration = time
          }
          that.setData({
            stopMyCar: res.data.data[0],
            stopCarInfoList: res.data.data
          })
          if (isOut) {
            that.setData({
              stopCarOutDialog: true
            })
          } else {
            that.setData({
              stopParkDialog: true
            })
            that.getStopingCar(false)
          }
          payCurrOrderFlag = false
        }
        currOrderFlag = false
      })
      .catch(err => {
        wx.showToast({
          title: '',
          icon: 'none',
          duration: 1
        })
        that.setData({
          stopCarDialog: true,
          stopCarOutDialog: false,
          stop_car_tips: err.data.desc
        })
        currOrderFlag = false
      })
  },
  /**
   * 关闭停车信息弹窗
   */
  hiddenStopParkDialog() {
    this.setData({
      stopParkDialog: false
    })
  },
  /**
   * 点击刷新位置
   */
  toMineBtn() {
    if (refFlag) {
      return
    }
    refFlag = true
    let that = this;
    let longitude = that.data.longitude;
    let latitude = that.data.latitude;
    that.setData({
      searchPlace: {},
      showMarkerModal: false
    })
    clearInterval(stopingTimer)
    that.getParks(longitude, latitude);
    that.getCustomerLeftTime()
    that.getArrearsOrder()  //  获取垫付订单
  },
  //右上角分享功能
  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: '',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onShareTimeline() {
    return {
      title: '',
      query: '/pages/index/index'
    }
  },
  /**
   * 关闭弹窗
   */
  closeMarkerModal() {
    let that = this
    this.setData({
      showMarkerModal: false,
      unfoldRule: false
    })
    setTimeout(function () {
      that.setData({
        parkImgCurr: 0,
        parkInfoImageL: 0,
        markerPark: {}
      })
    }, 300)
  },
  /**
   * 从历史记录导航
   * @param {*} event 
   */
  historyToMap(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let searcheRecord = that.data.searcheRecord[index];
    let lat = searcheRecord.latitude
    let lng = searcheRecord.longitude
    let name = searcheRecord.place
    let address = searcheRecord.address
    let scale = 14
    this.openLocation(lat, lng, name, address, scale)
  },
  /**
   * 从车场详情导航
   */
  toMapNavigation() {
    let that = this;
    that.closeMarkerModal();
    let markerPark = that.data.markerPark;
    let lat = markerPark.latitude
    let lng = markerPark.longitude
    let name = markerPark.parkName
    let address = markerPark.parkAddress
    let scale = 14
    this.openLocation(lat, lng, name, address, scale)
  },
  /**
   * 搜索结果导航
   */
  searchingToMap(e) {
    let index = e.currentTarget.dataset.index;
    let searchingData = this.data.searching[index];
    let lat = searchingData.location.lat
    let lng = searchingData.location.lng
    let name = searchingData.title
    let address = searchingData.address
    let scale = 14
    this.openLocation(lat, lng, name, address, scale)
  },
  /**
   * 搜索结果导航
   */
  searchParkToMap(e) {
    let index = e.currentTarget.dataset.index;
    let searchingData = this.data.searchResult[index];
    let lat = searchingData.latitude
    let lng = searchingData.longitude
    let name = searchingData.parkName
    let address = searchingData.parkAddress
    let scale = 14
    this.openLocation(lat, lng, name, address, scale)
  },
  /**
   * 打开导航
   * @param {Number} lat 纬度
   * @param {Number} lng 经度
   * @param {String} name 地名
   * @param {String} address 地址
   * @param {Number} scale 缩放等级
   */
  openLocation(lat, lng, name, address, scale) {
    let latitude = Number(lat)
    let longitude = Number(lng)
    wx.openLocation({
      latitude,
      longitude,
      name: name,
      address: address,
      scale: scale
    })
  },
  /**
   * 操作底部导航显示与隐藏
   */
  setTabBar() {
    this.setData({
      showTabBar: !this.data.showTabBar,
      showMarkerModal: false,
      unfoldRule: false
    })
  },
  /**
   * 展开规则
   */
  unfoldRuleDetial() {
    this.setData({
      unfoldRule: !this.data.unfoldRule
    })
  },
  /**
   * 底部tab栏跳转
   * @param {*} e 
   */
  toPage(e) {
    let token = wx.getStorageSync('lmtc_token');
    if (token == null || token == "" || token == undefined) {
      if (e.currentTarget.dataset.path == '/pages/center/center') {
        Toast('请先授权');
        return
      }
    }
    if (e.currentTarget.dataset.path == '/pages/index/index') {
      return
    }
    wx.redirectTo({
      url: e.currentTarget.dataset.path,
    })
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始位置经纬度
   * @param {Array} to 终点位置经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  // 预出场
  getsocket() {
    if (payCurrOrderFlag) {
      return
    }
    let _this = this;
    if (!_this.data.stopMyCar.orderCode) {
      return
    }
    let params = {
      orderCode: _this.data.stopMyCar.orderCode
    }
    wx.showLoading({
      title: '等待出场',
    })
    request.http('/order/orderInfo/prePayCurrOrder', 'POST', params, 1, false)
      .then(res => {
        log.info('接口/order/orderInfo/prePayCurrOrder:' + JSON.stringify(res.data))
        if (res.data.code == 200) {
          _this.getPaySuccess(res.data.data)
        }
      })
  },
  /**
   * 根据交易流水号查询订单是否支付成功
   */
  getPaySuccess(data) {
    let that = this
    let url = '/order/orderInfo/getOrderTradeRecordByTradeNo'
    let parmas = {
      orderCode: data.order_id,
      tradeNo: data.trade_no
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        log.info('接口' + url + ':' + JSON.stringify(res.data))
        if (res.data.code == 200) {
          wx.showToast({
            title: '请在15分钟内离场，超时将重新计费',
            duration: 3000,
            icon: 'none',
            success(res) {
              that.getStopingCar()
              that.hiddenStopParkDialog()
              that.setData({
                stopCarDialog: true,
                stopCarOutDialog: false,
                stop_car_tips: '请在15分钟内离场，超时将重新计费',
              })
            }
          })
        }
      })
  },
  /**
   * 打开socket
   */
  openSocket() {
    let _this = this;
    // 创建websocket对象
    this.websocket = new websocket({
      // true代表启用心跳检测和断线重连
      heartCheck: true,
      isReconnection: true
    });
    // 建立连接
    this.linkWebsocket();
    // 监听websocket状态
    this.websocket.onSocketClosed({
      url: this.data.websocketUrl,
      success(res) { console.log(res) },
      fail(err) { console.log(err) }
    })
    // 监听网络变化
    this.websocket.onNetworkChange({
      url: this.data.websocketUrl,
      success(res) { console.log(res) },
      fail(err) { console.log(err) }
    })
    // 监听服务器返回
    this.websocket.onReceivedMsg(result => {
      console.log('app.js收到服务器内容：' + result.data);
      if (result.data == 'ok') {
        // wx.hideLoading()
        _this.hiddenStopParkDialog()
        wx.showToast({
          title: '请在15分钟内离场，超时将重新计费',
          duration: 5000,
          icon: 'none'
        })
        clearInterval(countTime)
      }
      if (result.data == 'buy-card-success') {
        wx.hideLoading()
        wx.redirectTo({
          url: '../grade/grade'
        })
      }
      if ((result.data).indexOf('car-in-park') != -1) {
        setTimeout(function () {
          _this.toMineBtn()
        }, 1000)
      }
      if ((result.data).indexOf('car-out-park') != -1) {
        setTimeout(function () {
          _this.toMineBtn()
        }, 1000)
      }
      // 要进行的操作
    })
    // 监听websocket异常
    this.websocket.onSocketError({
      url: this.data.websocketUrl,
      success(res) {
        console.log("index-监听websocket异常成功", res)
      },
      fail(err) {
        console.log("监听websocket异常失败", res)
      }
    })
  },
  linkWebsocket() {
    let that = this
    // 建立连接
    this.websocket.initWebSocket({
      url: this.data.websocketUrl,
      success(res) {
        // that.countDown()
      },
      fail(err) { console.log(err) }
    })
  },
  onUnload() {
    clearTimeout(localTimeout)
    clearInterval(subInterval)
    clearInterval(addInterval)
    clearInterval(stopingTimer)
  },
  onHide() {
    clearInterval(stopingTimer)
  },
  // websocket超时处理
  countDown() {
    let count = 10
    let that = this
    countTime = setInterval(function () {
      count--
      if (count <= 0) {
        clearInterval(countTime)
        that.websocket.closeWebSocket();
        that.hiddenStopParkDialog()
        wx.showToast({
          title: '预出场失败，请重试',
          duration: 2000,
          icon: 'none'
        })
      }
    }, 1000)
  },
  /**
   * 实时位置监听
   */
  locationChange() {
    let that = this
    wx.startLocationUpdate({
      success: (res) => {
        wx.onLocationChange((result) => {
          var markers = this.data.markers
          for (var item of markers) {
            if (!item) {
              continue
            }
            if (item.id == 0) {
              item.latitude = result.latitude
              item.longitude = result.longitude
            }
          }
          that.setData({
            markers: markers
          })
        })
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },
  // 地图黑白切换
  changeStyle() {
    let that = this
    let hours = new Date().getHours()
    let mapStyle = that.data.mapStyle
    if (hours >= 19 || hours <= 6) {
      mapStyle = 4
    }
    that.setData({
      mapStyle: mapStyle
    })
    setTimeout(function () {
      that.changeStyle()
    }, 60000)
  },
  /**
   * 关闭停车信息弹窗
   */
  hiddenStopCarDialog() {
    this.setData({
      stopCarDialog: false
    })
  },
  hiddenStopCarOutDialog() {
    this.setData({
      stopCarOutDialog: false
    })
    this.getStopingCar(false)
  },
  closePopup(){
    this.setData({
      payBehalfDialog: false
    })
  },
  /**
   * 显示离场车辆
   */
  showStopCar() {
    let stopCar = this.data.stopingCar
    if (stopCar.length > 1) {
      stopCar[0].checked = true
      this.setData({
        stopCarOutDialog: true,
        stopingCar: stopCar
      })
    }
    this.getCurrOrder(0, true)
  },
  /**
   * 选择停放车辆
   */
  stopCarChange(e) {
    let value = e.detail.value
    let stopCar = this.data.stopingCar
    let index
    for (var i = 0; i < stopCar.length; i++) {
      stopCar[i].checked = false
      if (stopCar[i].carNumber == value) {
        index = [i]
      }
    }
    stopCar[index].checked = true
    this.setData({
      stopingCar: stopCar
    })
    this.getCurrOrder(index, true)
  },
  /**
   * 图片预览
   */
  showImage(e) {
    let markerPark = this.data.markerPark
    wx.previewImage({
      urls: markerPark.parkImgUrl.split(','),
      current: e.currentTarget.dataset.img
    })
  },
  /**
   * 图片切换
   */
  parkImgChange(e) {
    this.setData({
      parkImgCurr: e.detail.current
    })
  },
  /**
   * 变换地图样式
   */
  changeMapStyle() {
    this.setData({
      mapStyle: this.data.mapStyle == 2 ? 4 : 2
    })
  },
  /**
   * 获取新发放优惠券
   */
  getCouponTips() {
    let that = this
    let url = '/customer/ticket/getTipsTicket'
    let parmas = {
      customerId: wx.getStorageSync('lmtc_customerId')
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          if (data.data.length > 0) {
            that.setData({
              couponTipList: data.data,
              couponTipsDialog: true
            })
          }
        }
      })
  },
  /**
   * 取消优惠券提示
   */
  closeCouponTips() {
    let that = this
    let url = '/ticket/updateTipsStatus'
    let parmas = {
      customerId: wx.getStorageSync('lmtc_customerId')
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            couponTipsDialog: false
          })
        }
      })
  },
  /** 
   * 优惠券
  */
  toCoupon(e) {
    this.closeCouponTips()
    wx.navigateTo({
      url: e.currentTarget.dataset.path,
    })
  },
  bindtouchstart(e) {
    let touchStartX = e.changedTouches[0].pageX
    this.setData({
      touchStartX: touchStartX
    })
  },
  bindtouchend(e) {
    let parkImgUrl = this.data.markerPark.parkImgUrl.split(',')
    let touchStartX = this.data.touchStartX
    let touchEndX = e.changedTouches[0].pageX
    let left = 0
    let parkImgCurr = this.data.parkImgCurr
    if (parkImgUrl.length <= 1) {
      return
    }
    if (touchStartX - touchEndX > 50) {
      if (parkImgUrl.length - 1 <= parkImgCurr) return
      parkImgCurr += 1
      left = -700 * parkImgCurr
    } else if (touchStartX - touchEndX < -50) {
      if (parkImgCurr <= 0) return
      parkImgCurr -= 1
      left = -700 * parkImgCurr
    }
    this.setData({
      touchEndX: touchEndX,
      parkInfoImageL: left,
      parkImgCurr: parkImgCurr
    })
  },
  /**
   * 跳转预约页面
   */
  toSubscribe() {
    wx.navigateTo({
      url: '/pages/subscribe/subscribe?homeSbuBtn=true',
    })
  }
})